import type { RouteLocationNormalized, Router } from "vue-router";
import { usePermissionStoreHook } from "@/store/modules";

const whiteRoutes: string[] = ["/login", "/exception/404"];

function permission(
  to: RouteLocationNormalized,
  _from: RouteLocationNormalized,
  router: Router
) {
  if (whiteRoutes.includes(to.path)) {
    return true;
  }

  const permissionStore = usePermissionStoreHook();
  permissionStore.setCookies();
  if (!permissionStore.getCookies) {
    window["$message"].warning("登录已失效，请重新登录");
    return { path: "/login" };
  }

  // 判断当前路由（to）是否存在于路由表中
  const findResource = (routes: any) =>
    routes?.some((r: any) => r?.name === to.name || findResource(r?.children));

  const hasResource = findResource(router.options.routes);

  // 不存在，重定向到 404
  if (!hasResource) {
    return { name: "exception-404" };
  }
  // 存在，继续
  return true;
}

export default permission;
